package com.glsc.ngateway.flowable.listener.demandmanagement;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.api.flowable.dto.ParamEmailDto;
import com.glsc.ngateway.common.api.flowable.dto.demand.ArrangeInf;
import com.glsc.ngateway.common.api.flowable.dto.demand.FlowableDemandDto;
import com.glsc.ngateway.common.base.domain.mysql.flowable.FlowableDemand;
import com.glsc.ngateway.common.base.domain.mysql.flowable.FlowableEhrEmp;
import com.glsc.ngateway.flowable.service.FlowableDemandService;
import com.glsc.ngateway.flowable.service.FlowableEhrEmpService;
import com.glsc.ngateway.flowable.service.MailService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.task.service.delegate.DelegateTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class DemandManagementArrangeHandler implements TaskListener, ApplicationContextAware {

    private static final Logger logger = LoggerFactory.getLogger(DemandManagementArrangeHandler.class);


    @Autowired
    private RuntimeService runtimeService;

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext arg0) throws BeansException {
        applicationContext = arg0;
    }


    @Override
    public void notify(DelegateTask delegateTask) {

        try {
            FlowableDemandService flowableDemandService = (FlowableDemandService) applicationContext.getBean("flowableDemandService");
            String content = delegateTask.getVariable("content").toString();
            JSONObject json = JSONObject.parseObject(content);
            JSONObject demandSubmit = json.getJSONObject("demandSubmit");
            String title = json.getString("title");
            FlowableDemand demand = JSON.parseObject(demandSubmit.toJSONString(), FlowableDemand.class);
            List<FlowableDemandDto> exist = flowableDemandService.findByProcessInstanceId(delegateTask.getProcessInstanceId());
            FlowableDemandDto demandExist = exist.get(0);
            if (demandExist != null) {
                List<ArrangeInf> alist = JSONObject.parseArray(demand.getArrangeinfo(), ArrangeInf.class);
                for (ArrangeInf l : alist) {
                    FlowableEhrEmpService flowableEhrEmpService = (FlowableEhrEmpService) applicationContext.getBean("flowableEhrEmpService");
                    if (flowableEhrEmpService != null) {
                        l.setDevUserName(flowableEhrEmpService.getChineseName(l.getDevUserId()));
                    }
                }
                String arrange = JSONObject.toJSONString(alist);
                demandExist.setArrangeinfo(arrange);
                flowableDemandService.saveDemandSubmit(demandExist);

                try {
                    logger.info("需求管理排期，发送通知邮件开始。需求人:" + demandExist.getStaff());
                    MailService mailService = (MailService) applicationContext.getBean("mailService");
                    FlowableEhrEmpService flowableEhrEmpService = (FlowableEhrEmpService) applicationContext.getBean("flowableEhrEmpService");
                    FlowableEhrEmp emp = flowableEhrEmpService.getUserInfo(demandExist.getStaff());
                    if (emp != null) {
                        ParamEmailDto dto = new ParamEmailDto();
                        dto.setContext(createHtmlContent(demandExist.getDemandDetail(), title));
                        dto.setTitle("需求管理系统通知-需求已排期");
                        dto.setRecipient(emp.getEmail());
                        mailService.sendEmail(dto);
                        logger.info("需求管理排期，发送通知邮件结束。收件email:" + emp.getEmail());
                    } else {
                        logger.info("需求管理排期，未发送通知邮件。未找到该用户邮箱。" + demandExist.getStaff());
                    }
                } catch (Exception e) {
                    logger.error("DemandManagementArrangeHandler发送邮件异常，主流程继续。processid=" + delegateTask.getProcessInstanceId(), e);
                }
            }
        } catch (Exception e) {
            logger.error("DemandManagementArrangeHandler处理异常，结束处理。processid=" + delegateTask.getProcessInstanceId(), e);
            throw new RuntimeException("DemandManagementArrangeHandler处理异常，结束处理。processid=" + delegateTask.getProcessInstanceId(), e);
        }
    }

    private String createHtmlContent(String demand, String title) {
        return "<html lang='en' style='margin: 0; padding: 0; font-family: Helvetica Neue, Microsoft Yahei, Hiragino Sans GB, WenQuanYi Micro Hei, sans-serif; font-size: 14px; text-align: center; word-break: normal; font-weight: normal;'>"
                + "<head>"
                + "<style type='text/css'>body {border-width:0;margin:0}img {border:0;margin:0;padding:0}</style><base target='_blank' />"
                + "</head>"
                + "<p>您好：</p>"
                + "<p>     您所提交的需求已经完成排期。    </p>"
                + "<p>     需求标题： " + title + "     </p>"
                + "<p>     需求描述： " + demand + "    </p>"
                + "</html>";
    }

}